package com.bw.lib_net.interceptor

import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okio.Buffer
import java.nio.charset.StandardCharsets

/**
 * @author ykj
 * @date 2025-09-16 21:19
 * @description
 * * (1)生成签名：请求体--》字符串 +密钥盐 --》MD5 -->签名
 *  * (2)添加签名请求头:x-api-sign:签名
 */
class SignInterceptor: Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val  request = chain.request()
        val builder = request.newBuilder()
        //请求体--》字符串
        val str =  bodyToString(request)
        val sign = createSign(str, "78525211")
        builder.addHeader("x-api-sign", sign)
        return chain.proceed(builder.build())
    }

    /**
     * 请求体--》字符串
     */
    fun bodyToString(request: Request): String {
        val buffer = Buffer()
        request.body?.writeTo(buffer)
        return buffer.readUtf8()
    }

    /**
     * MD5加密
     * salt:密钥盐
     */
    fun createSign(json:String, salt:String):String{
        val buffer = Buffer()
        buffer.write(json.toByteArray(StandardCharsets.UTF_8))
        buffer.write(salt.toByteArray(StandardCharsets.UTF_8))
        //md5加密
        return buffer.md5().hex() //十六进制
    }
}